<template>
  <el-collapse-item title="区域" name="area">
    <el-form size="mini" :inline="true">
      <el-form-item v-for="({ key, label }, index) in styleKeys" :key="index" :label="label" label-width="45px">
        <el-input v-model.number="curComponent[key]" type="number" @input="validateAreaValue($event, key)" />
      </el-form-item>
    </el-form>
  </el-collapse-item>
</template>

<script>
import {
  areaData,
  textAlignOptions,
  borderStyleOptions,
  verticalAlignOptions,
  selectKey,
  optionMap,
} from '@/utils/attr'
import { get } from 'lodash'
import { changeStyleWithScale } from '@/utils/translate'
import { mapState } from 'vuex'

export default {
  name: 'CommonAttr',
  data() {
    return {
      optionMap,
      areaData,
      textAlignOptions,
      borderStyleOptions,
      verticalAlignOptions,
      selectKey,
      activeName: '',
    }
  },
  computed: {
    ...mapState(['curCanvasPageIndex', 'canvasStyleData']),
    styleKeys() {
      if (this.curComponent) {
        const curComponentStyleKeys = Object.keys(this.curComponent)
        return this.areaData.filter((item) => curComponentStyleKeys.includes(item.key))
      }

      return []
    },
    curComponent() {
      return this.$store.state.curComponent
    },
    canvasStyle() {
      return get(this.canvasStyleData, `[${this.curCanvasPageIndex}]`) || {}
    },
    canvasWidth() {
      return changeStyleWithScale(get(this.canvasStyle, 'width') || 0, this.lastScale)
    },
    canvasHeight() {
      return changeStyleWithScale(get(this.canvasStyle, 'width') || 0, this.lastScale)
    },
  },
  methods: {
    validateAreaValue(value, key) {
      const { left = 0, top = 0, width = 0, height = 0 } = this.curComponent

      if (left < 0 || top < 0) {
        this.curComponent[key] = 0
      }

      if (width < 0 || height < 0) {
        this.curComponent[key] = 0
      }
      console.log('', key, this.canvasStyleData, width)
      switch (key) {
        case 'top':
          if (top + height > this.canvasHeight) {
            this.curComponent[key] = this.canvasHeight - height
          }
          break
        case 'left':
          if (left + width > this.canvasWidth) {
            this.curComponent[key] = this.canvasWidth - width
          }
          break
        case 'width':
          if (width + left > this.canvasWidth) {
            this.curComponent[key] = this.canvasWidth - left
          }
          break
        case 'height':
          if (height + top > this.canvasHeight) {
            this.curComponent[key] = this.canvasHeight - top
          }
          break
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.el-form--inline {
  .el-form-item {
    width: 105px;
    display: inline-flex;
  }
}
</style>
